package com.eascs.admin.o2o.backfee.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.excel.ExcelService;
import com.eascs.admin.o2o.backfee.entity.FormBackFeeEntity;
import com.eascs.admin.o2o.backfee.service.O2OComBankFeeService;
import com.eascs.afterloan.controller.O2oAfterLoanController;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.notice.controller.NoticeBaseMasterController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.service.sys.SysOrgService;

@Controller
@RequestMapping("/backfee")
public class O2oComBackFeeController extends NoticeBaseMasterController  {
	
	private static Logger logger = LoggerFactory.getLogger(O2oComBackFeeRestController.class);
	
	@Autowired
	O2OComBankFeeService o2oComBankFeeService;
	@Reference
	SysOrgService sysOrgService;
	
	@RequestMapping("/index")
	public String index(FormBackFeeEntity entity){
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "com_backfee");
		StringBuffer o2oPageUrl = new StringBuffer("/rbackfee/o2obackfee");
		String o2oUrl = "";
		String backfeeReportUrl="/backfee/bzjglfExport";
		if (entity != null) {
			String billCode = entity.getBill_code() == null ? "" : entity.getBill_code();
			String userName = entity.getName() == null ? "" : entity.getName();
			String payMentStatus = entity.getPayMentStatus() == null ? "" : entity.getPayMentStatus();
			o2oUrl = UrlUtil.appendUrl(o2oPageUrl.toString(), "bill_code", billCode);
			o2oUrl = UrlUtil.appendUrl(o2oUrl, "name", userName);
			o2oUrl = UrlUtil.appendUrl(o2oUrl, "payMentStatus", payMentStatus);
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "bill_code",billCode);
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "name",userName);
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "payMentStatus",payMentStatus);
		}
		o2oUrl = o2oUrl + "&showO2oPage=";
		StringBuffer oaPageUrl = new StringBuffer("/rbackfee/oabackfee");
		String oaUrl = "";
		if (entity != null) {
			String billCode = entity.getBill_code() == null ? "" : entity.getBill_code();
			String userName = entity.getName() == null ? "" : entity.getName();
			String payMentStatus = entity.getPayMentStatus() == null ? "" : entity.getPayMentStatus();
			oaUrl = UrlUtil.appendUrl(oaPageUrl.toString(), "bill_code", billCode);
			oaUrl = UrlUtil.appendUrl(oaUrl, "name", userName);
			oaUrl = UrlUtil.appendUrl(oaUrl, "payMentStatus", payMentStatus);
		}
		oaUrl = oaUrl + "&showOaPage=";
		ViewContext.put("o2oBackfeeUrl", o2oUrl);
		ViewContext.put("oaBackfeeUrl", oaUrl);
		ViewContext.put("backfeeReportUrl", backfeeReportUrl);
		ViewContext.put("vo", entity);
		return "/backfee/bond_expense";
	}
	
	// 查询退费流程信息页面
	
	@SuppressWarnings("unused")
	@RequestMapping(value = "/list")
	public String list(FormBackFeeEntity entity) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "bzjls");
		entity.setPageSize(10);
		
		List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		logger.info("userno={}", no);
		entity.setXdjlNo(no);
		
		
		String url = "/backfee/list";
		String backfeeReportUrl = "/backfee/download";
		if (null != entity) {
			String billCode = entity.getBill_code() == null ? "" : entity.getBill_code();
			String name = entity.getName() == null ? "" : entity.getName();
			url = UrlUtil.appendUrl(url, "bill_code", billCode);
			url = UrlUtil.appendUrl(url, "name", name);
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "bill_code", billCode);
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "name", name);
			url = url + "&showO2oPage=";
		} else {
			url = url + "?showO2oPage=";
		}
		PageResult<Object[]> pageResult = o2oComBankFeeService.findByPageList(entity);
		SelectDataOption[] selectDataOptions = { null,  null, null, null, null, null,null,null,new SelectDataOption("BILLSTATUS")};
		String[] titles = { "单据号", "借款人姓名", "退费开户银行名称", "退费银行账", "退费账户户名", "退风险补偿金金额", "退管理费金额", "退保证金金额", "状态" };
		Button[] findButton = new Button[] { ButtonHelper.createAjaxButton(null, "/rbackfee/backfeeView?billCode=billCode&referId="), null };
//		Button star = ButtonHelper.createAjaxButton("启动流程", "/combackfeesubmit/backfeestartup?referId=");
//		star.setShowButtonFilter(new ShowButtonFilter() {
//			@Override
//			public boolean filter(Object arg0) {
//				Object []param = (Object[]) arg0;
//				if(param[9].equals(StatusContexts.O2O_NEW)){
//					return true;
//				}
//				return false;
//			}
//		});
//		Button[] startButton = new Button[] {star};
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, url);
		paginationInfo.setTitleButtons(findButton);
//		paginationInfo.setMoreButtons(startButton);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setFormats(new Format[] { null, null, null,null,null, new DecimalFormat(",##0.00"),new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null });
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("vo", entity);
		ViewContext.put("backfeeReportUrl", backfeeReportUrl);
		return "/backfee/index";
	}
	
	@RequestMapping("/download")
	public void dowanload(FormBackFeeEntity entity,HttpServletResponse httpServletResponse, HttpServletRequest request) {
		entity.setPageSize(Integer.MAX_VALUE);
		
		
		/*List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		logger.info("userno={}", no);
		entity.setXdjlNo(no);*/
		
		PageResult<Object[]> pageResult = o2oComBankFeeService.findByPageReportList(entity);
		String path = O2oComBackFeeController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/backfee-model.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "退费列表.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), O2oComBackFeeController.class.getResourceAsStream("/excelTemplate/backfee-model.xls"), defaultRowWriteHandler);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
//		return result;
	}
	
	//先生成文件然后在读这个文件
		public String saveBackFee(List<Object[]> data) {
			//模板
			String soucreFileName = "/excelTemplate/backfee-model.xls";
			//输出路径
			String path = O2oAfterLoanController.class.getResource("/excelTemplate").getPath();
			StringBuffer s = new StringBuffer();
			String outPath = s.append(path).append("/backfee.xls").toString();
			int col = 10;
			//需要统计的列
			int[] arr = {};
			String title = "单据号";
			//开始的表格，行，列
			int sheetIndex=0;
			int rowIndex=1;
			int columnIndex=0;
			//生产excel
			new ExcelService().writeByDate(soucreFileName, outPath, col,arr,Arrays.asList(title),sheetIndex,rowIndex,columnIndex,data);
			//存放的文件的文件夹
			return path+"/"+outPath;
		}
		
		/**
		 * @Title: dowanload
		 * @Description: 保证金管理费导出
		 * @author 张庆奇
		 * @param entity
		 * @param httpServletResponse
		 * @param request
		 * @return void
		 * @throws
		 * @date 2017年3月31日 上午9:47:05
		 */
		@RequestMapping("/bzjglfExport")
		public void bzjglfExport(FormBackFeeEntity entity,HttpServletResponse httpServletResponse, HttpServletRequest request) {
			entity.setPageSize(Integer.MAX_VALUE);
			entity.setFlag("export");
			
			List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
			String no="";
			if (users!=null) {
				for (User user : users) {
					no+=user.getNo()+",";
				}
			}
			if (!"".equals(no)) {
				if (",".equals(no.substring(no.length()-1, no.length()))) {
					no=no.substring(0, no.length()-1);
				}
			}
			logger.info("userno={}", no);
			entity.setXdjlNo(no);
			
			PageResult<Object[]> pageResult = o2oComBankFeeService.findBzjglfExport(entity);
			String path = O2oComBackFeeController.class.getResource("/excelTemplate").getPath();
			StringBuffer s = new StringBuffer();
			String outPath = s.append(path).append("/bzjGlf-model.xls").toString();
			OutputStream os = null;
			try {
				String outfile = "保证金管理费列表.xls";
				String userAgent = request.getHeader("User-Agent");
				byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
				outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
				File f = new File(outPath);
				if (!f.exists())
					throw new RuntimeIOException("file not found");
				os = httpServletResponse.getOutputStream();
				httpServletResponse.reset();
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
				httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
				DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
				ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), O2oComBackFeeController.class.getResourceAsStream("/excelTemplate/bzjGlf-model.xls"), defaultRowWriteHandler);
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				IoUtil.fileToOutputStream(f, byteArrayOutputStream);
				os.write(byteArrayOutputStream.toByteArray());
				os.flush();
			} catch (IOException e) {
				throw new RuntimeIOException(e);
			} finally {
				IoUtil.close(os);
			}
//			return result;
		}
		
		
	
	
}
